 import { useState, useEffect } from 'react';
import {
  Button,
  Input,
  Checkbox,
  Text,
  Label,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  Spinner,
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  DialogClose,
} from 'packages/ui-shared/src/atoms';
import { useSession } from '../hooks/useSession';
import { useCollegeManagement } from '../hooks/useCollegeManagement';
import { College } from '../mock/collegeData';
import { mockTeachers } from '../mock/teacherData';

const CollegeManagementPage = () => {
  const { session } = useSession();
  const [isAddOpen, setIsAddOpen] = useState(false);
  const [isEditOpen, setIsEditOpen] = useState(false);
  const [isDeleteOpen, setIsDeleteOpen] = useState(false);
  const [isDetailOpen, setIsDetailOpen] = useState(false);
  const [currentCollege, setCurrentCollege] = useState<College | null>(null);
  const [collegeStaff, setCollegeStaff] = useState({
    dean: '',
    viceDean: '',
    officeManager: '',
    departmentHead: '',
    counselorCount: 0,
    lecturerCount: 0
  });
  const [form, setForm] = useState({
    name: '',
    dean: '',
    contactNumber: '',
    description: '',
    departmentCount: '0',
    studentCount: '0',
    teacherCount: '0',
    counselorCount: '0',
    lecturerCount: '0',
  });

  // 使用学院管理hook
  const {
    paginatedColleges,
    loading,
    error,
    searchTerm,
    currentPage,
    pageSize,
    totalPages,
    selectedColleges,
    selectAll,
    stats,
    setSearchTerm,
    setCurrentPage,
    setPageSize,
    toggleCollegeSelection,
    toggleSelectAll,
    batchDelete,
    loadColleges,
    service
  } = useCollegeManagement();

  // 权限检查
  const canEdit = session?.userRole === 'admin' || session?.userRole === 'user';
  const canDelete = session?.userRole === 'admin';
  const canAdd = session?.userRole === 'admin';

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    if (name === 'counselorCount' || name === 'lecturerCount' || name === 'departmentCount' || name === 'studentCount' || name === 'teacherCount') {
      setForm(prev => ({
        ...prev,
        [name]: parseInt(value) || 0
      }));
    } else {
      setForm(prev => ({
        ...prev,
        [name]: value
      }));
    }
  };

  // 处理添加学院
  const handleAdd = async () => {
    if (!form.name.trim()) {
      alert('请输入学院名称');
      return;
    }

    try {
      const collegeData = {
        name: form.name.trim(),
        dean: form.dean.trim(),
        location: '', // 保留此字段以兼容数据结构
        contactNumber: form.contactNumber.trim(),
        description: form.description.trim(),
        departmentCount: parseInt(form.departmentCount) || 0,
        studentCount: parseInt(form.studentCount) || 0,
        teacherCount: parseInt(form.teacherCount) || 0,
        establishedYear: '', // 保留此字段以兼容数据结构
        counselorCount: form.counselorCount || 0,
        lecturerCount: form.lecturerCount || 0
      };

      await service.addCollege(collegeData);
      await loadColleges();
      setIsAddOpen(false);
      resetForm();
    } catch (err) {
      console.error('添加学院失败:', err);
      alert('添加学院失败: ' + (err instanceof Error ? err.message : '未知错误'));
    }
  };

  // 处理编辑学院
  const handleEdit = async () => {
    if (!currentCollege || !form.name.trim()) {
      alert('请输入学院名称');
      return;
    }

    try {
      const collegeData = {
        name: form.name.trim(),
        dean: form.dean.trim(),
        contactNumber: form.contactNumber.trim(),
        description: form.description.trim(),
        departmentCount: parseInt(form.departmentCount) || 0,
        studentCount: parseInt(form.studentCount) || 0,
        teacherCount: parseInt(form.teacherCount) || 0,
        counselorCount: form.counselorCount || 0,
        lecturerCount: form.lecturerCount || 0
      };

      await service.updateCollege(currentCollege.id, collegeData);
      await loadColleges();
      setIsEditOpen(false);
      setCurrentCollege(null);
      resetForm();
    } catch (err) {
      console.error('编辑学院失败:', err);
      alert('编辑学院失败: ' + (err instanceof Error ? err.message : '未知错误'));
    }
  };

  // 计算辅导员和讲师数量
  useEffect(() => {
    if (currentCollege) {
      // 从mockTeachers中统计辅导员和讲师数量
      const counselors = mockTeachers.filter(teacher => 
        teacher.managedClasses.some(cls => cls.collegeId === currentCollege.id) && 
        teacher.role === 'counselor'
      );
      const lecturers = mockTeachers.filter(teacher => 
        teacher.managedClasses.some(cls => cls.collegeId === currentCollege.id) && 
        teacher.role === 'lecturer'
      );

      // 设置学院管理人员信息（这里使用模拟数据）
      setCollegeStaff({
        dean: currentCollege.dean,
        viceDean: '刘教授', // 模拟数据
        officeManager: '陈主任', // 模拟数据
        departmentHead: '周教授', // 模拟数据
        counselorCount: counselors.length,
        lecturerCount: lecturers.length
      });
    }
  }, [currentCollege]);

  // 打开详情对话框
  const handleDetailOpen = (college: College) => {
    setCurrentCollege(college);
    setIsDetailOpen(true);
  };

  // 处理删除学院
  const handleDelete = async () => {
    if (!currentCollege) return;

    try {
      await service.deleteCollege(currentCollege.id);
      await loadColleges();
      setIsDeleteOpen(false);
      setCurrentCollege(null);
    } catch (err) {
      console.error('删除学院失败:', err);
      alert('删除学院失败: ' + (err instanceof Error ? err.message : '未知错误'));
    }
  };

  // 打开编辑对话框
  const handleEditOpen = (college: College) => {
    setCurrentCollege(college);
    setForm({
      name: college.name,
      dean: college.dean,
      contactNumber: college.contactNumber,
      description: college.description,
      departmentCount: college.departmentCount.toString(),
      studentCount: college.studentCount.toString(),
      teacherCount: college.teacherCount.toString(),
      counselorCount: college.counselorCount ? college.counselorCount : 0,
      lecturerCount: college.lecturerCount ? college.lecturerCount : 0,
    });
    setIsEditOpen(true);
  };

  // 打开删除对话框
  const handleDeleteOpen = (college: College) => {
    setCurrentCollege(college);
    setIsDeleteOpen(true);
  };

  // 重置表单
  const resetForm = () => {
    setForm({
      name: '',
      dean: '',
      contactNumber: '',
      description: '',
      departmentCount: '0',
      studentCount: '0',
      teacherCount: '0',
      counselorCount: 0,
      lecturerCount: 0,
    });
  };

  return (
    <div className="p-6">
      <div className="flex flex-col gap-6">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <h1 className="text-2xl font-bold">学院管理</h1>
            <p className="text-muted-foreground">管理学校的所有学院信息</p>
          </div>
          {canAdd && (
            <Button onClick={() => setIsAddOpen(true)}>
              添加学院
            </Button>
          )}
        </div>

        {/* 搜索和筛选 */}
        <div className="flex flex-col sm:flex-row gap-4">
          <div className="relative flex-1">
            <Input
              type="text"
              placeholder="搜索学院名称、院长或位置..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full"
            />
          </div>
        </div>

        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <div className="bg-card p-4 rounded-lg border">
            <p className="text-muted-foreground">学院总数</p>
            <p className="text-2xl font-bold mt-1">{stats.total}</p>
          </div>
          <div className="bg-card p-4 rounded-lg border">
            <p className="text-muted-foreground">学生总数</p>
            <p className="text-2xl font-bold mt-1">{stats.studentTotal}</p>
          </div>
          <div className="bg-card p-4 rounded-lg border">
            <p className="text-muted-foreground">教师总数</p>
            <p className="text-2xl font-bold mt-1">{stats.teacherTotal}</p>
          </div>
          <div className="bg-card p-4 rounded-lg border">
            <p className="text-muted-foreground">系部总数</p>
            <p className="text-2xl font-bold mt-1">{stats.departmentTotal}</p>
          </div>
        </div>

        {/* 表格内容 */}
        {loading ? (
          <div className="flex justify-center items-center p-8">
            <Spinner size="lg" />
            <span className="ml-2">加载中...</span>
          </div>
        ) : error ? (
          <div className="bg-destructive/10 text-destructive p-4 rounded-lg">
            {error}
          </div>
        ) : (
          <div className="overflow-hidden border rounded-lg">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>
                    <Checkbox
                      checked={selectAll && paginatedColleges.length > 0}
                      onCheckedChange={toggleSelectAll}
                      aria-label="Select all"
                    />
                  </TableHead>
                  <TableHead>学院名称</TableHead>
                  <TableHead>院长</TableHead>
                  <TableHead>联系电话</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {paginatedColleges.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center">
                      暂无数据
                    </TableCell>
                  </TableRow>
                ) : (
                  paginatedColleges.map((college) => (
                    <TableRow key={college.id}>
                      <TableCell>
                        <Checkbox
                          checked={selectedColleges.includes(college.id)}
                          onCheckedChange={() => toggleCollegeSelection(college.id)}
                          aria-label={`Select ${college.name}`}
                        />
                      </TableCell>
                      <TableCell>{college.name}</TableCell>
                      <TableCell>{college.dean}</TableCell>
                      <TableCell>{college.contactNumber}</TableCell>
                      <TableCell>
                        <div className="flex gap-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleDetailOpen(college)}
                          >
                            详情
                          </Button>
                          {canEdit && (
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleEditOpen(college)}
                            >
                              编辑
                            </Button>
                          )}
                          {canDelete && (
                            <Button
                              variant="ghost"
                              size="sm"
                              className="text-destructive"
                              onClick={() => handleDeleteOpen(college)}
                            >
                              删除
                            </Button>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        )}

        {/* 分页控制 */}
        <div className="flex items-center justify-between">
          <div className="text-sm text-muted-foreground">
            显示 {(currentPage - 1) * pageSize + 1} - 
            {Math.min(currentPage * pageSize, paginatedColleges.length)} / 
            {paginatedColleges.length} 条
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
              disabled={currentPage === 1}
            >
              上一页
            </Button>
            <span className="text-sm">{currentPage} / {totalPages}</span>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
              disabled={currentPage === totalPages || totalPages === 0}
            >
              下一页
            </Button>
          </div>
        </div>
      </div>

      {/* 添加学院对话框 */}
      <Dialog open={isAddOpen} onOpenChange={setIsAddOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>添加学院</DialogTitle>
            <DialogDescription>
              填写学院信息并保存
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="name" className="text-right">
                学院名称
              </Label>
              <Input
                id="name"
                name="name"
                value={form.name}
                onChange={handleInputChange}
                className="col-span-3"
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="dean" className="text-right">
                院长
              </Label>
              <Input
                id="dean"
                name="dean"
                value={form.dean}
                onChange={handleInputChange}
                className="col-span-3"
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="contactNumber" className="text-right">
                联系电话
              </Label>
              <Input
                id="contactNumber"
                name="contactNumber"
                value={form.contactNumber}
                onChange={handleInputChange}
                className="col-span-3"
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="counselorCount" className="text-right">
                辅导员数量
              </Label>
              <Input
                id="counselorCount"
                name="counselorCount"
                type="number"
                min="0"
                value={form.counselorCount}
                onChange={handleInputChange}
                className="col-span-3"
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="lecturerCount" className="text-right">
                讲师数量
              </Label>
              <Input
                id="lecturerCount"
                 name="lecturerCount"
                type="number"
                min="0"
                value={form.lecturerCount}
                onChange={handleInputChange}
                className="col-span-3"
              />
            </div>
          </div>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="ghost">取消</Button>
            </DialogClose>
            <Button onClick={handleAdd}>保存</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 编辑学院对话框 */}
      <Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>编辑学院</DialogTitle>
            <DialogDescription>
              修改学院信息并保存
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-name" className="text-right">
                学院名称
              </Label>
              <Input
                id="edit-name"
                name="name"
                value={form.name}
                onChange={handleInputChange}
                className="col-span-3"
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-dean" className="text-right">
                院长
              </Label>
              <Input
                id="edit-dean"
                name="dean"
                value={form.dean}
                onChange={handleInputChange}
                className="col-span-3"
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-contactNumber" className="text-right">
                联系电话
              </Label>
              <Input
                id="edit-contactNumber"
                name="contactNumber"
                value={form.contactNumber}
                onChange={handleInputChange}
                className="col-span-3"
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-counselorCount" className="text-right">
                辅导员数量
              </Label>
              <Input
                id="edit-counselorCount"
                name="counselorCount"
                type="number"
                min="0"
                value={form.counselorCount}
                onChange={handleInputChange}
                className="col-span-3"
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-lecturerCount" className="text-right">
                讲师数量
              </Label>
              <Input
                id="edit-lecturerCount"
                name="lecturerCount"
                type="number"
                min="0"
                value={form.lecturerCount}
                onChange={handleInputChange}
                className="col-span-3"
              />
            </div>
          </div>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="ghost">取消</Button>
            </DialogClose>
            <Button onClick={handleEdit}>保存</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除学院对话框 */}
      <Dialog open={isDeleteOpen} onOpenChange={setIsDeleteOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认删除</DialogTitle>
            <DialogDescription>
              您确定要删除这个学院吗？此操作无法撤销。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="ghost">取消</Button>
            </DialogClose>
            <Button variant="destructive" onClick={handleDelete}>
              删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 学院详情对话框 */}
      <Dialog open={isDetailOpen} onOpenChange={setIsDetailOpen}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle>学院详情</DialogTitle>
            <DialogDescription>
              {currentCollege?.name} 的详细信息
            </DialogDescription>
          </DialogHeader>
          {currentCollege && (
            <div className="grid gap-6 py-4">
              {/* 学院基本信息 */}
              <div className="bg-card/50 p-4 rounded-lg border">
                <h3 className="font-semibold mb-3">基本信息</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <p className="text-sm text-muted-foreground">学院名称</p>
                    <p className="font-medium">{currentCollege.name}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">联系电话</p>
                    <p>{currentCollege.contactNumber}</p>
                  </div>
                  {currentCollege.description && (
                    <div className="col-span-2">
                      <p className="text-sm text-muted-foreground">学院简介</p>
                      <p>{currentCollege.description}</p>
                    </div>
                  )}
                </div>
              </div>

              {/* 学院管理人员 */}
              <div className="bg-card/50 p-4 rounded-lg border">
                <h3 className="font-semibold mb-3">管理人员</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <p className="text-sm text-muted-foreground">院长</p>
                    <p className="font-medium">{collegeStaff.dean}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">副院长</p>
                    <p>{collegeStaff.viceDean}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">院办</p>
                    <p>{collegeStaff.officeManager}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">主任</p>
                    <p>{collegeStaff.departmentHead}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">辅导员数量</p>
                    <p className="font-medium text-lg">{collegeStaff.counselorCount}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">讲师数量</p>
                    <p className="font-medium text-lg">{collegeStaff.lecturerCount}</p>
                  </div>
                </div>
              </div>
            </div>
          )}
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="ghost">关闭</Button>
            </DialogClose>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default CollegeManagementPage;